from flask import Flask, request,render_template, redirect, session, send_file, url_for, make_response
from flask_session import Session
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField
import os

from common_utils import *
import json
from tmp_file_clean import *

commentsFileName= "%s_commnets_%s.json"
keywordFile = "%s_keywordresult_%s.json"
excel_file_path = '%s_valid_comments_%s.xlsx'
xhsconfig = "xhs_config.json"

f_session = Session()
app = Flask(__name__)

app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['SECRET_KEY'] = 'laowangaigebi'  # encode key
app.config['SESSION_USE_SIGNER'] = True  # encode
app.config['SESSION_TYPE'] = 'filesystem'  # type filesystem
app.config['SESSION_KEY_PREFIX'] = 'session:'  # prefix
app.config['PERMANENT_SESSION_LIFETIME'] = 7200#s
#app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port='6379', db=4)  # redis数据库连接
f_session.init_app(app)

app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB

class UploadForm(FlaskForm):
    photo = FileField(validators=[
        FileAllowed(photos, u'only image'), 
        FileRequired(u'no image be selected')])
    submit = SubmitField(u'submit')

    # form = UploadForm()
    # if form.validate_on_submit():
    #     filename = photos.save(form.photo.data)
    #     file_url = photos.url(filename)
    # else:
    #     file_url = None


def is_login():
    uuid = session.get("uuid")
    if not uuid or uuid.strip() == "":
        return False 
    return True

def __gen_return__(template):
    uuid = session.get('uuid')
    isLogin = True if uuid  else False
    
    logger.info(f"the login: {uuid} , credits :{credits}")

    return render_template(template, isLogin=isLogin, credits=credits)

#---------to page----------- 
@app.route('/split', methods=['GET'])
def split():
    return __gen_return__("split.html")

@app.route('/card', methods=['GET'])
def card():
    return __gen_return__("card.html")


@app.route('/dropin', methods=['GET'])
def dropin():
    return __gen_return__("dropin.html")

@app.route('/getdetail', methods=['POST']) 
def getdetail():
    logger.info(request.get_json())
    jsonData = request.get_json()
    id = jsonData.get('id')

    if not id  or id.strip() == '':
        logger.info(f"put session,and email= {session.get('email')}")
        return {"code":"error", "msg":"需要输入ID"}, 200
    else:
        
        config = {}
        configId = None
        notesData = {}
        comments = {}
        try:
            with open((keywordFile % (id, 'current')), "r") as file:
                notesData = json.load(file)
                file.close()

        except Exception as e:
            logger.warning(e)


        try:
            with open(commentsFileName %(id, 'current'), "r") as file:
                comments = json.load(file)
                file.close()
        except Exception as e:
            logger.warning(e)

        try:
            with open("xhs_config.json", "r") as file:
                config =json.load(file)
                file.close()

            configId = config[id]
        except Exception as e:
            logger.warning(e)
        
        status, ret = Cmd(f"ps -fe |grep xhs_main_{id}.py |grep -v grep").execute_cmd()
        logger.info(f"check status:{status}, ret {ret}")
        if not status:
           status, ret = Cmd(f"python3.12 /Users/yanchaoxi/work_ycx/sourecode/xhs-master/xhs_main_{id}.py").execute_cmd()
           logger.info(f"start parsing xhs:{status}, ret {ret}")

        sortedComments = sorted(comments.items(), key=lambda item: item[1]['no'])

        return {"code":'success', "config":configId ,"notes": notesData, "comments":sortedComments}, 200
    
    
@app.route('/update', methods=['POST']) 
def active():

    logger.info(request.get_json())

    jsonData = request.get_json()

    keyword = jsonData.get("keyword");
    validTime = jsonData.get("commentTime");
    limit_count = jsonData.get("limit_count");
    cookie = jsonData.get("cookie");
    id = jsonData.get('id')

    if not id  or id.strip() == '':
        logger.info(f"put session,and email= {session.get('email')}")
        return {"code":"error", "msg":"需要输入ID"}, 200
    else:
        config = {}
        try:
            with open("xhs_config.json", "r") as file:
                config =json.load(file)
                file.close()

            logger.warning(f"the last config :{config}")
            logger.warning(f"the id {id}, new kewords: {keyword}, validTime:{validTime}, limit_count:{limit_count}, cookie : {cookie}")

            config[id]['cookie'] = cookie if cookie else config[id]['cookie']
            config[id]['limit_count'] = int(limit_count) if limit_count else config[id]['limit_count']
            config[id]['keywords'] = keyword if keyword else config[id]['keywords']
            config[id]['validTime'] = int(validTime) if validTime else config[id]['validTime']
            config[id]['updateTime'] = time.time()
            config[id]['errorTime'] = 0

            with open("xhs_config.json", "w") as file:
               json.dump(config, file, indent=4, ensure_ascii=False)
               file.close()

        except Exception as e:
            logger.warning(e)
        
        return {"code":'success', "config":config[id]}, 200


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=7777, debug=True)